package com.lowca.news.service.impl;

import javax.annotation.Resource;

import org.hibernate.Hibernate;
import org.springframework.dao.DataAccessException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.lowca.news.dao.UserDao;
import com.lowca.news.entity.User;
import com.lowca.news.service.support.UserDetailsAdapter;

@Service("userDetailsService")
@Transactional(readOnly = true)
public class UserDetailsServiceImpl implements UserDetailsService {

	@Resource
	private UserDao userDao;

	public UserDao getUserDao() {
		return userDao;
	}

	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}

	@Override
	public UserDetails loadUserByUsername(String username)
			throws UsernameNotFoundException, DataAccessException {
		User user = userDao.findByUsername(username);
		if (user == null) {
			throw new UsernameNotFoundException("用户名 " + username + " 不存在");
		}
		Hibernate.initialize(user.getRoles());
		return new UserDetailsAdapter(user);
	}

}
